<template>
    <el-dialog v-model="show" title="添加退货原因" width="30%" center @close="emit('hide')">
        <div class="content">
            <el-form ref="searchFormRef" :model="state.list">
                <el-form-item label="原因类型：" label-width="120px">
                    <el-input style="width:300px" v-model="state.list.name" />
                </el-form-item>
                <el-form-item label="排序：" label-width="120px">
                    <el-input style="width:300px" v-model="state.list.sort" />
                </el-form-item>
                <el-form-item label="是否启用：" label-width="120px">
                    <template #default="scope">
                        <el-switch v-model="list.status" :active-value="1" :inactive-value="0" />
                    </template>
                </el-form-item>
            </el-form>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="emit('hide')">取消</el-button>
                <el-button type="primary" @click="sureFn">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, toRefs, watch } from 'vue'
import { FormInstance } from "element-plus"
import { user } from '@/api';

// 创建表单实例
const searchFormRef = ref<FormInstance>()

const props = defineProps({
    show: {
        type: Boolean,
        default: true,
    },
    editId: {
        type: Number,
        default: 0
    }
})

// 父传过来的取消方法
const emit = defineEmits(['hide', 'refsh'])



// 点击添加
interface IAddReason {
    list: IReturnReasonList
}

const state = reactive<IAddReason>({
    list: {
        createTime: "",
        id: 0,
        name: "",
        sort: 0,
        status: 0
    }
})

const sureFn = () => {
    if (props.editId !== 0) {
        user.getUpdateReasonApi(state.list).then((res) => {
            if (res.code === 200) {
                emit("hide")
                emit('refsh')
            }
        })
    } else {
        user.getCreateReasonApi(state.list).then((res) => {
            if (res.code === 200) {
                emit("hide")
                emit('refsh')
            }
        })
    }

}

// watch监听
watch(
    () => props.editId,
    () => {
        if (props.editId === 0) {
            state.list = {
                createTime: "",
                id: 0,
                name: "",
                sort: 0,
                status: 0
            }
            return
        }
        // console.log(props.editId);
        user.getReasonIdApi(props.editId).then((res) => {
            if (res.code === 200) {
                // 把数据给回去
                // console.log(res.data);
                Object.assign(state.list, res.data)
                // console.log(list);

            }
        })
    }
)


let { list } = toRefs(state)
</script>
<style lang="less" scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>